<?php

namespace SC\Admin\Widgets;


class Form extends Panel
{
    protected $model = null;
    protected $id = null;
    protected $isDisplay = false;
    protected $payload = [];

    public function __construct($model, $id, $display=false)
    {
        $this->model = $model;
        $this->id = $id;
        $this->isDisplay = $display;
    }

    public function display($display=true)
    {
        $this->isDisplay = $display;
    }

    public function payload($payload)
    {
        $this->payload = \array_merge($this->payload, $payload);
    }

    public function viewCtx()
    {
        $resource = (new $this->model)->getTable();
        $values = [];
        if ($this->id) {
            $query = $this->model::where(function(){});
            if ($this->query) {
                $this->query->bindTo($query)();
            }
            $payload = $query->findOrFail($this->id);
            $values = $this->fieldsValue($payload);
        }

        return [
            'elId' => $this->elId(),
            'title' => $this->title,
            'actions' => $this->actions(),
            'isDisplay' => $this->isDisplay,
            'resource' => $resource,
            'id' => $this->id,
            'fields' => $this->fieldsMeta(),
            'values' => $values,
            'payload' => $this->payload,
        ];
    }

    public function view()
    {
        return $this->isDisplay ? 'admin::widgets.display': 'admin::widgets.form';
    }
}